"""
description: 基于DS18B20传感器的温度监测系统
"""

import machine
import ubinascii
import onewire, ds18x20
import time

# 设备ID
CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode("utf-8")
# MQTT 主题路径
TOPIC = "device/temperature/{}".format(CLIENT_ID)
TOPIC = TOPIC.encode()
temp_client = None

# 定义传感器的引脚
ds_pin = machine.Pin(13)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))


def read_ds_sensor():
    roms = ds_sensor.scan()
    # print("发现设备: ", roms)
    ds_sensor.convert_temp()
    time.sleep_ms(750)  # 等待转换完成
    for rom in roms:
        temp = ds_sensor.read_temp(rom)
        if isinstance(temp, float):
            temp = round(temp, 2)
            return temp


def temperature_callback(t):
    temp = read_ds_sensor()
    if temp is not None:
        print("温度: ", temp)
        temp_client.publish(TOPIC, str(temp))
        return temp
    else:
        print("未检测到温度传感器")
        temp_client.publish(TOPIC, str(0))
        return 0


def register_Temperature_topic(client):
    global temp_client
    temp_client = client
    # temp_client.subscribe(TOPIC)
    # 安排温度读取的定时器，每10秒执行一次
    # temp_timer = machine.Timer(0)
    # temp_timer.init(
    #     period=60000, mode=machine.Timer.PERIODIC, callback=temperature_callback
    # )
